package com.example.demo.controller;

import com.example.demo.auth.service.impl.SysCaptchaServiceImpL;
import com.example.demo.entity.vo.CaptchVo;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class CaptchaController {

    @Resource
    SysCaptchaServiceImpL  sysCaptchaServiceImpL;

    @Resource
    private Producer producer;

    /**
     * 测试 获取验证码的controller
     * @param session
     * @param response
     */
    @RequestMapping(value = "/cap",method = RequestMethod.GET)
    public void kaptcha(HttpSession session, HttpServletResponse response){

        //生成验证码
        String text = producer.createText();
        //生成的验证码信息放在session中。
        session.setAttribute("cap_key",new CaptchVo(text,60*2));
        //生成验证码图片
        BufferedImage image = producer.createImage(text);

        response.setContentType(MediaType.IMAGE_JPEG.getType());
        try {
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            ImageIO.write(image, "jpeg", os);
            os.writeTo(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("验证码获取失败", e);
        }

    }
}

